package com.loongtech.bi.action.newsystem;

import com.alibaba.fastjson.JSONObject;
import com.loongtech.bi.action.authManagement.ResultData;
import com.loongtech.bi.entity.POJO.Page;
import com.loongtech.bi.entity.system.EntityBiChannel;
import com.loongtech.bi.entity.system.EntityBiServer;
import com.loongtech.bi.entity.system.EntitySysProject;
import com.loongtech.bi.manager.system.BiPlatformManager;
import com.loongtech.bi.manager.system.BiServerManager;
import com.loongtech.bi.manager.system.SyncInfoLogManager;
import com.loongtech.bi.manager.system.SysProjectManager;
import com.loongtech.core.util.RetCode;
import com.loongtech.core.util.Time;
import com.loongtech.core.util.Utils;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author: yuri
 * Description: 区服配置管理
 * Date: 20:18 2017/5/25
 */
@RestController
@Scope("prototype")
@RequestMapping("/serverconfig")
public class ServerManagementAction {
    @Resource
    private BiPlatformManager biPlatformManager;
    @Resource
    private BiServerManager biServerManager;
    @Resource
    private SyncInfoLogManager syncInfoLogManager;
    @Resource
    private SysProjectManager sysProjectManager;


    /**
     * 查询区服渠道下拉列表
     */
    @RequestMapping(value = "channellist.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<?> searchByCriteria(@RequestParam Integer gameId) {
        if (gameId == null) {
            return new ResultData<>(RetCode.eEmptyId.getErrorcode(), RetCode.eEmptyId.getErrorMsg());
        }
        List<EntityBiChannel> list;
        try {
            list = biServerManager.findByQuery("select id, name from EntityBiChannel where gameId = ?", gameId);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultData.otherException();
        }
        return new ResultData<>(RetCode.eSuccess.getErrorcode(), list);
    }

    @RequestMapping(value = "getlist.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<?> getlist(@RequestParam Integer curPage, @RequestParam Integer pageSize, EntityBiServer entity) {
        try {
            Map<String, Object> params = new HashMap<>();
            EntitySysProject project = sysProjectManager.getByQuery("from EntitySysProject where id = ?", entity.getGameId());
            params.put("curPage", curPage);
            params.put("pageSize", pageSize);
            if (project == null) {
                return new ResultData<>(RetCode.eEmptyProject.getErrorcode(), RetCode.eEmptyProject.getErrorMsg());
            }
            String url = project.getProjectUrl() + "/serverconfig/list.do";
            String res = Utils.httpPost(url, params);
            JSONObject json = com.alibaba.fastjson.JSONObject.parseObject(res);
            if (json.getIntValue("code") == 0) {
                return new ResultData<>(RetCode.eSuccess.getErrorcode(), json);
            } else {
                return ResultData.otherException();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultData.otherException();
        }
    }

    @RequestMapping(value = "list.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<?> search(@RequestParam Integer curPage, @RequestParam Integer pageSize, EntityBiServer entity) {
        Page<List<EntityBiServer>> list;
        try {
            list = biServerManager.queryByCriteria(curPage, pageSize, entity);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultData.otherException();
        }
        return new ResultData<>(RetCode.eSuccess.getErrorcode(), list);
    }

    @RequestMapping(value = "add.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<String> add(EntityBiServer entity) {
        try {
            List<EntityBiServer> list = biServerManager.findAll();
            ResultData<String> res = validate(true, entity, list);
            if (res != null) {
                return res;
            }
            biServerManager.persist(entity);
            syncInfoLogManager.add(entity.getGameId().toString(), "insert into bi_server(id,gameId,name,serverType,description,channelIds,capacity,used,updateAt) values" +
                    "(" + "'" + entity.getId() + "','" + entity.getGameId() + "','" + entity.getName() + "','" + entity.getServerType() + "','" + entity.getDescription() + "','" + entity.getChannelIds() + "'," + entity.getCapacity() + "," + entity.isUsed() + "," + Time.currentTime() + ")");
            biPlatformManager.init();
            return ResultData.success();
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultData.otherException();
        }
    }

    @RequestMapping(value = "modify.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<String> modify(EntityBiServer entity) {
        try {
            List<EntityBiServer> list = biServerManager.findAll();
            ResultData<String> res = validate(false, entity, list);
            if (res != null) {
                return res;
            }
            EntityBiServer cur = biServerManager.get(entity.getId());
            if (cur != null) {
                biServerManager.merge(entity);
                syncInfoLogManager.add(entity.getGameId().toString(), "update bi_server set gameId = " + entity.getGameId() + ",name = '"
                        + entity.getName() + "',serverType = '" + entity.getServerType() + "',description = '" + entity.getDescription() + "',channelIds = '" + entity.getChannelIds() + "',capacity = " + entity.getCapacity() + ", used = " + entity.isUsed() + ",updateAt = " + Time.currentTime() + " where id = '" + entity.getId() + "'");
                biPlatformManager.init();
                return ResultData.success();
            } else {
                return new ResultData<>(RetCode.eNotExistGourp.getErrorcode(), RetCode.eNotExistGourp.getErrorMsg());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultData.otherException();
        }
    }

    @RequestMapping(value = "delete.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<String> delete(String id) {
        try {
            EntityBiServer cur = biServerManager.get(id);
            if (cur != null) {
                biServerManager.removeById(id);
                syncInfoLogManager.add(cur.getGameId().toString(), "delete from bi_server where id = '" + cur.getId() + "'");
                biPlatformManager.init();
                return ResultData.success();
            } else {
                return new ResultData<>(RetCode.eNotExistGourp.getErrorcode(), RetCode.eNotExistGourp.getErrorMsg());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultData.otherException();
        }
    }

    private ResultData<String> validate(Boolean isAdd, EntityBiServer ebp, List<EntityBiServer> ebpList) {
        if (ebp.getGameId() == null) {
            return new ResultData<>(RetCode.eEmptyGameId.getErrorcode(), RetCode.eEmptyGameId.getErrorMsg());
        }
        if (Utils.isEmptyStr(ebp.getId())) {
            return new ResultData<>(RetCode.eEmptyId.getErrorcode(), RetCode.eEmptyId.getErrorMsg());
        }
        if (Utils.isEmptyStr(ebp.getName())) {
            return new ResultData<>(RetCode.eNotExistName.getErrorcode(), RetCode.eNotExistName.getErrorMsg());
        }
        if (Utils.isEmptyStr(ebp.getServerType())) {
            return new ResultData<>(RetCode.eEmptySerGroup.getErrorcode(), RetCode.eEmptySerGroup.getErrorMsg());
        }
        if (Utils.isEmptyStr(ebp.getChannelIds())) {
            return new ResultData<>(RetCode.eEmptySerChannel.getErrorcode(), RetCode.eEmptySerChannel.getErrorMsg());
        }
        if (isAdd) {  // 如果是添加，则ID与名称皆不能重
            for (EntityBiServer e : ebpList) {
                if (ebp.getId().equals(e.getId()) && ebp.getGameId().equals(e.getGameId())) {
                    return new ResultData<>(RetCode.eIdExist.getErrorcode(), RetCode.eIdExist.getErrorMsg());
                }
                if (ebp.getName().equals(e.getName())) {
                    return new ResultData<>(RetCode.eNameExist.getErrorcode(), RetCode.eNameExist.getErrorMsg());
                }
            }
        } else {  // 如果是修改，则名称不能重
            for (EntityBiServer e : ebpList) {
                if (!ebp.getId().equals(e.getId()) && ebp.getName().equals(e.getName()) && ebp.getGameId().equals(e.getGameId())) {
                    return new ResultData<>(RetCode.eNameExist.getErrorcode(), RetCode.eNameExist.getErrorMsg());
                }
            }
        }
        return null;
    }
}
